package com.example;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.stage.FileChooser;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.example.AdminUserDialogController;
import com.example.User;
import com.example.UserDAO;

public class AdminUserManagementController {
    @FXML private ComboBox<String> userTypeComboBox;
    @FXML private TextField searchField;
    @FXML private TableView<User> userTableView;
    @FXML private TableColumn<User, String> usernameColumn;
    @FXML private TableColumn<User, String> nameColumn;
    @FXML private TableColumn<User, String> typeColumn;
    @FXML private TableColumn<User, String> departmentColumn;
    @FXML private TableColumn<User, String> statusColumn;
    @FXML private TableColumn<User, Void> actionColumn;

    private ObservableList<User> userList = FXCollections.observableArrayList();
    private UserDAO userDAO = new UserDAO(); // 创建UserDAO实例
    private AdminController adminController; // 添加对AdminController的引用

    public void setAdminController(AdminController adminController) {
        this.adminController = adminController;
    }

    @FXML
    public void initialize() {
        // 初始化用户类型下拉框
        userTypeComboBox.setItems(FXCollections.observableArrayList("全部", "教师", "学生"));
        userTypeComboBox.getSelectionModel().selectFirst();

        // 初始化表格列
        usernameColumn.setCellValueFactory(new PropertyValueFactory<>("username"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        typeColumn.setCellValueFactory(new PropertyValueFactory<>("type"));
        departmentColumn.setCellValueFactory(new PropertyValueFactory<>("department"));
        statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));

        // 添加操作列按钮
        actionColumn.setCellFactory(createActionButtonCellFactory());

        // 设置表格数据
        userTableView.setItems(userList);

        // 加载初始数据
        loadUserData();
    }

    private Callback<TableColumn<User, Void>, TableCell<User, Void>> createActionButtonCellFactory() {
        return new Callback<>() {
            @Override
            public TableCell<User, Void> call(TableColumn<User, Void> param) {
                return new TableCell<>() {
                    private final Button editButton = new Button("编辑");
                    private final Button deleteButton = new Button("删除");
                    private final HBox buttons = new HBox(5, editButton, deleteButton);

                    {
                        editButton.setOnAction(event -> {
                            User user = getTableView().getItems().get(getIndex());
                            handleEditUser(user);
                        });

                        deleteButton.setOnAction(event -> {
                            User user = getTableView().getItems().get(getIndex());
                            handleDeleteUser(user);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        setGraphic(empty ? null : buttons);
                    }
                };
            }
        };
    }

    // 公共方法：从数据库加载用户数据并刷新表格
    public void loadUserData() {
        try {
            userList.clear();
            // 从数据库加载用户数据
            userList.addAll(userDAO.getAllUsers());
        } catch (SQLException e) {
            e.printStackTrace();
            showError("加载用户数据失败：" + e.getMessage());
        }
    }

    @FXML
    private void handleSearch() {
        String searchText = searchField.getText().trim();
        String selectedType = userTypeComboBox.getValue();

        try {
            userList.clear();
            // 根据搜索条件从数据库查询用户
            userList.addAll(userDAO.searchUsers(searchText, selectedType));
        } catch (SQLException e) {
            e.printStackTrace();
            showError("搜索用户失败：" + e.getMessage());
        }
    }

    @FXML
    private void handleAddUser() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("AdminUserDialog.fxml"));
            Parent root = loader.load();
            AdminUserDialogController controller = loader.getController();

            Stage dialogStage = new Stage();
            dialogStage.setTitle("添加用户");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.setScene(new Scene(root));

            controller.setDialogStage(dialogStage);
            controller.setUser(null);

            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                User newUser = controller.getUser();
                // 保存到数据库
                try {
                    userDAO.addUser(newUser);
                    loadUserData(); // 刷新列表
                } catch (SQLException e) {
                    e.printStackTrace();
                    showError("添加用户失败：" + e.getMessage());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            showError("打开添加用户对话框失败");
        }
    }

    private void handleEditUser(User user) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("AdminUserDialog.fxml"));
            Parent root = loader.load();
            AdminUserDialogController controller = loader.getController();

            Stage dialogStage = new Stage();
            dialogStage.setTitle("编辑用户");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.setScene(new Scene(root));

            controller.setDialogStage(dialogStage);
            controller.setUser(user);

            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                User updatedUser = controller.getUser();
                // 更新数据库
                try {
                    userDAO.updateUser(updatedUser);
                    loadUserData(); // 刷新列表
                } catch (SQLException e) {
                    e.printStackTrace();
                    showError("更新用户失败：" + e.getMessage());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            showError("打开编辑用户对话框失败");
        }
    }

    private void handleDeleteUser(User user) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("删除用户");
        alert.setContentText("确定要删除用户 " + user.getName() + " 吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            // 从数据库删除
            try {
                userDAO.deleteUser(user.getUsername());
                loadUserData(); // 刷新列表
            } catch (SQLException e) {
                e.printStackTrace();
                showError("删除用户失败：" + e.getMessage());
            }
        }
    }

    @FXML
    private void handleImportUsers() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择Excel文件");
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Excel文件", "*.xlsx", "*.xls")
        );

        File file = fileChooser.showOpenDialog(userTableView.getScene().getWindow());
        if (file != null) {
            try {
                List<User> importedUsers = importUsersFromExcel(file);
                if (!importedUsers.isEmpty()) {
                    // 批量保存到数据库
                    for (User user : importedUsers) {
                        try {
                            userDAO.addUser(user);
                        } catch (SQLException e) {
                            showError("导入用户 " + user.getUsername() + " 失败: " + e.getMessage());
                        }
                    }
                    loadUserData(); // 刷新列表
                    showSuccess("成功导入 " + importedUsers.size() + " 个用户");
                }
            } catch (IOException e) {
                showError("读取Excel文件失败: " + e.getMessage());
            }
        }
    }

    private List<User> importUsersFromExcel(File file) throws IOException {
        List<User> users = new ArrayList<>();
        try (Workbook workbook = WorkbookFactory.create(file)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过表头

                try {
                    User user = new User(
                        getCellValueAsString(row.getCell(0)), // 用户名
                        getCellValueAsString(row.getCell(1)), // 姓名
                        getCellValueAsString(row.getCell(2)), // 类型
                        getCellValueAsString(row.getCell(3)), // 院系
                        "正常", // 默认状态
                        getCellValueAsString(row.getCell(4))  // 密码
                    );
                    users.add(user);
                } catch (Exception e) {
                    showError("第 " + (row.getRowNum() + 1) + " 行数据格式错误: " + e.getMessage());
                }
            }
        }
        return users;
    }

    private String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING: return cell.getStringCellValue();
            case NUMERIC: return String.valueOf((int)cell.getNumericCellValue());
            default: return "";
        }
    }

    @FXML
    private void handleExportUsers() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("保存Excel文件");
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Excel文件", "*.xlsx")
        );
        fileChooser.setInitialFileName("用户列表.xlsx");

        File file = fileChooser.showSaveDialog(userTableView.getScene().getWindow());
        if (file != null) {
            try {
                exportUsersToExcel(file);
                showSuccess("成功导出用户数据");
            } catch (IOException e) {
                showError("导出Excel文件失败: " + e.getMessage());
            }
        }
    }

    private void exportUsersToExcel(File file) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("用户列表");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户名", "姓名", "类型", "院系", "状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 写入数据
            int rowNum = 1;
            for (User user : userList) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(user.getUsername());
                row.createCell(1).setCellValue(user.getName());
                row.createCell(2).setCellValue(user.getType());
                row.createCell(3).setCellValue(user.getDepartment());
                row.createCell(4).setCellValue(user.getStatus());
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 保存文件
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                workbook.write(fileOut);
            }
        }
    }

    private void showError(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    private void showSuccess(String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("成功");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
} 